package com.xyy.saas.payment.service.job.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.adapter.channel.WxCommonAdapter;
import com.xyy.saas.payment.adapter.channel.fm.config.YBMSpringConfiguration;
import com.xyy.saas.payment.callback.CallbackUtil;
import com.xyy.saas.payment.common.constants.BaseConstants;
import com.xyy.saas.payment.common.constants.ChannelConstants;
import com.xyy.saas.payment.common.constants.ChannelProductConstants;
import com.xyy.saas.payment.constants.Constants;
import com.xyy.saas.payment.cores.enums.BusinessPayTypeEnum;
import com.xyy.saas.payment.cores.enums.FBankPowerIdEnum;
import com.xyy.saas.payment.cores.enums.OpenAccountAuthorizeStatusEnum;
import com.xyy.saas.payment.cores.enums.OpenPayStatusEnum;
import com.xyy.saas.payment.pojo.bo.PayAmountReportBO;
import com.xyy.saas.payment.pojo.param.PayAmountReportParam;
import com.xyy.saas.payment.cores.vo.BusinessPayQueryVo;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.dao.model.*;
import com.xyy.saas.payment.enums.BusinessPayStatusEnum;
import com.xyy.saas.payment.enums.FBankTradeTypeEnum;
import com.xyy.saas.payment.enums.FrozenStatusEnum;
import com.xyy.saas.payment.exception.PaymentException;
import com.xyy.saas.payment.manage.cores.enums.BusinessOrderTypeEnum;
import com.xyy.saas.payment.manage.cores.enums.BusinessTypeEnum;
import com.xyy.saas.payment.manage.cores.enums.ChannelEnum;
import com.xyy.saas.payment.manage.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.pojo.bo.BusinessPayQueryBo;
import com.xyy.saas.payment.pojo.vo.BusinessPayVo;
import com.xyy.saas.payment.service.*;
import com.xyy.saas.payment.service.job.OrderJobService;
import com.xyy.saas.payment.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderJobServiceImpl implements OrderJobService {
    @Resource
    private FrozenSettlementService frozenSettlementService;
    @Resource
    private PayResultOrderService payResultOrderService;
    @Resource
    private ThirdUserInfoService thirdUserInfoService;
    @Resource
    private YBMSpringConfiguration ybmSpringConfiguration;
    @Autowired
    private BusinessRecordService businessRecordService;
    @Autowired
    private WxCommonAdapter wxCommonAdapter;
    @Autowired
    private CallbackUtil callbackUtil;
    @Autowired
    private PayAmountReportService payAmountReportService;
    @Autowired
    private ApplyOpenAccountStatusService applyOpenAccountStatusService;
    @Autowired
    private OpenpayInfoService openpayInfoService;
    @Autowired
    private ApplypayUserInfoService applypayUserInfoService;

    /**
     * 生成待冻结单据
     * @param businessOrderType
     * @param startTime
     * @param endTime
     */
    @Override
    public void genFrozenSettlementOrder(String businessOrderType, Date startTime, Date endTime) {
        log.info("FrozenSettlementService#genFrozenSettlementOrder，start" +
                        "businessOrderType={}, startTime={}, endTime={}", businessOrderType,
                DateUtil.format(startTime, DateUtil.DATEFORMATSECOND), DateUtil.format(endTime, DateUtil.DATEFORMATSECOND));

        // 1.参数校验
        if(StringUtils.isBlank(businessOrderType) || startTime == null || endTime == null)  {
            log.error("FrozenSettlementService#genFrozenSettlementOrder，param is empty.");
            return;
        }

        // 2.交易数据统计
        List<PayResultOrder> items =  payResultOrderService.sumAmountByOrderType(businessOrderType, ChannelConstants.CHANNEL_FUMIN_BANK_NAME, startTime, endTime);

        if(CollectionUtils.isEmpty(items)) {
            log.info("FrozenSettlementService#genFrozenSettlementOrder，items is empty.");
            return;
        }

        Map<String, List<PayResultOrder>> tempGroupItems = items.stream(). collect(Collectors.groupingBy(PayResultOrder::getReceiveId));

        // 3.写入数据
        tempGroupItems.forEach((key, val) -> {
            try {
                genFrozenSettlementOrder0(key, businessOrderType, val);
            }
            catch(Exception ex) {
                log.error(ex.getMessage() + ", genFrozenSettlementOrder0 error key=" + key + " ,val=" + JSONObject.toJSONString(val), ex);
            }
        });
    }

    @Override
    public void checkWxBusinessStatus() {
        //查询5天-1小时前的订单
        Date beginTime = DateUtil.getDayAfterToday(-5, 0);
        Date endTime = DateUtil.getDayAfterToday(0, -1);
        int pageSize = 50;
        int totalCount = businessRecordService.countBusinessRecordPoByStatus(BusinessPayStatusEnum.CREATE_SUCCESS.getCode(), beginTime, endTime);
        int pageSum = PageUtil.getPageSum(totalCount, pageSize);
        for (int pageNum = 1; pageNum <= pageSum; pageNum++) {
            int pageOffset = PageUtil.getPageOffset(pageNum, pageSize);
            List<BusinessRecordPo> changes = new ArrayList<>();
            List<BusinessRecordPo> recordPos = businessRecordService.queryBusinessRecordPoByStatus
                    (BusinessPayStatusEnum.CREATE_SUCCESS.getCode(), beginTime, endTime, pageOffset, pageSize);
            recordPos.forEach(e->handleBusinessRecord(e, changes));
            if (!CollectionUtils.isEmpty(changes)) {
                businessRecordService.updateRecordsStatus(changes);
                callBackChanges(changes);
            }
        }
    }

    @Override
    public void syncPayAmountReport(PayAmountReportParam param) {
        log.info("OrderJobServiceImpl#syncPayAmountReport start. param:{}", JSONUtils.toJSON(param));
        if(null == param.getStartTime() || null == param.getEndTime() || param.getStartTime().after(param.getEndTime())) {
            log.warn("OrderJobServiceImpl#syncPayAmountReport time error. startTime:{}, endtime:{}", param.getStartTime(), param.getEndTime());
            return;
        }
        if(param.getEndTime().after(DateUtil.now())) {
            param.setEndTime(DateUtil.now());
        }
        try {
            List<String> times = DateUtil.getBetweenDates(param.getStartTime(), param.getEndTime(), DateUtil.DATEFORMATDAY);
            for (String countTime : times) {
                log.info("OrderJobServiceImpl#syncPayAmountReport start sync data for time:{}", countTime);
                List<PayResultOrder> payResultOrders = new ArrayList<>();
                try {
                    PayResultOrder queryParam = new PayResultOrder();
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(param.getBusinessOrderType())) {
                        queryParam.setBusinessType(param.getBusinessOrderType());
                    }
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(param.getBusinessType())) {
                        queryParam.setBusinessOrderType(param.getBusinessType());
                    }
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(param.getPayChannel())) {
                        queryParam.setPayChannel(param.getPayChannel());
                    }
                    // countTime 当天的起止时间
                    Date dayFirstTime = DateUtil.getDayFirstTime(DateUtil.parase(countTime, DateUtil.DATEFORMATDAY));
                    Date dayLastTime = DateUtil.getDayLastTime(DateUtil.parase(countTime, DateUtil.DATEFORMATDAY));
                    payResultOrders = payResultOrderService.queryCountAmountByParamGroup(queryParam, dayFirstTime, dayLastTime);
                } catch (PaymentException e) {
                    log.error("OrderJobServiceImpl#syncPayAmountReport error. e",e);
                    return;
                }
                if(!payResultOrders.isEmpty()) {
                    for (PayResultOrder payResultOrder : payResultOrders) {
                        log.info("OrderJobServiceImpl#syncPayAmountReport start sync data for businessType:{}, businessOrderType:{}, payChannel:{}", payResultOrder.getBusinessType(), payResultOrder.getBusinessOrderType(), payResultOrder.getPayChannel());
                        // 判断是否存在
                        PayAmountReportQueryParam queryParam = new PayAmountReportQueryParam();
                        queryParam.setBusinessOrderType(payResultOrder.getBusinessOrderType());
                        queryParam.setBusinessType(payResultOrder.getBusinessType());
                        queryParam.setPayChannel(payResultOrder.getPayChannel());
                        queryParam.setStartTime(countTime);
                        queryParam.setEndTime(countTime);
                        List<PayAmountReport> payAmountReports = payAmountReportService.queryByParam(queryParam);
                        if(payAmountReports.isEmpty()) {
                            PayAmountReport entity = new PayAmountReport();
                            entity.setBusinessType(payResultOrder.getBusinessType());
                            entity.setBusinessOrderType(payResultOrder.getBusinessOrderType());
                            entity.setPayChannel(payResultOrder.getPayChannel());
                            entity.setAmount(Long.valueOf(payResultOrder.getAmount()));
                            entity.setCountTime(countTime);
                            entity.setCreateTime(DateUtil.now());
                            entity.setUpdateTime(DateUtil.now());
                            payAmountReportService.insert(entity);
                        } else if (payAmountReports.size() > 1) {
                            log.error("OrderJobServiceImpl#syncPayAmountReport data repeat. payAmountReports:{}", JSONUtils.toJSON(payAmountReports));
                            log.info("OrderJobServiceImpl#syncPayAmountReport sync error for businessType:{}, businessOrderType:{}, payChannel:{}", payResultOrder.getBusinessType(), payResultOrder.getBusinessOrderType(), payResultOrder.getPayChannel());
                            break;
                        } else {
                            PayAmountReport payAmountReport = payAmountReports.get(0);
                            payAmountReportService.updateAmountById(payAmountReport.getId(), payResultOrder.getAmount());
                        }
                        log.info("OrderJobServiceImpl#syncPayAmountReport end sync data for businessType:{}, businessOrderType:{}, payChannel:{}", payResultOrder.getBusinessType(), payResultOrder.getBusinessOrderType(), payResultOrder.getPayChannel());
                    }
                }
                log.info("OrderJobServiceImpl#syncPayAmountReport end sync data for time:{}", countTime);
            }

        } catch (Exception e) {
            log.error("OrderJobServiceImpl#syncPayAmountReport exception.",e);
            return;
        }

        log.info("OrderJobServiceImpl#syncPayAmountReport finish.");
        syncPayAmountDictData();
        log.info("OrderJobServiceImpl#syncPayAmountReport syncPayAmountDictData finish.");
    }

    @Override
    public void syncPayAmountDictData() {
        Map<String, String> businessType = SpringUtils.getBean("payAmountReportBusinessType", Map.class);
        Map<String, String> businessOrderType = SpringUtils.getBean("payAmountReportBusinessOrderType", Map.class);
        Map<String, String> payChannelType = SpringUtils.getBean("payAmountReportChannelType", Map.class);

        Set<String> businessTypeSet = new HashSet<>();
        Set<String> businessOrderTypeSet = new HashSet<>();
        Set<String> payChannelTypeSet = new HashSet<>();

        int page = 1;
        PayAmountReportQueryParam param = new PayAmountReportQueryParam();
        param.setLimit(BaseConstants.DEFAULT_PAGE_SIZE);
        long total = payAmountReportService.getTotal(param);
        while(true) {
            param.setOffset((page-1)*100);
            List<PayAmountReport> payAmountReports = payAmountReportService.pageByGroupParam(param);

            List<PayAmountReportBO> data = new ArrayList<>();
            for (PayAmountReport payAmountReport : payAmountReports) {
                PayAmountReportBO payAmountReportBO = new PayAmountReportBO();
                BeanUtils.copyProperties(payAmountReport, payAmountReportBO);
                data.add(payAmountReportBO);
            }

            log.info("PayAmountReportApiImpl#pageByGroupParam end. resultData:{}", JSONUtils.toJSON(data));
            data.forEach(item -> {
                businessTypeSet.add(item.getBusinessType());
                businessOrderTypeSet.add(item.getBusinessOrderType());
                payChannelTypeSet.add(item.getPayChannel());
            });

            if(page*100 >= total) {
                break;
            }
            page++;
        }

        businessTypeSet.forEach(item -> {
            String value = item;
            if(BusinessTypeEnum.contains(item)) {
                value = BusinessTypeEnum.getEnum(item).getDesc();
            }
            businessType.put(item,value);
        });
        businessOrderTypeSet.forEach(item -> {
            String value = item;
            if(BusinessOrderTypeEnum.contains(item)) {
                value = BusinessOrderTypeEnum.getEnum(item).getDesc();
            }
            businessOrderType.put(item,value);
        });
        payChannelTypeSet.forEach(item -> {
            String value = item;
            if(ChannelEnum.contains(item)) {
                value = ChannelEnum.getChannelEnum(item).getName();
            }
            payChannelType.put(item,value);
        });
    }

    public void handleBusinessRecord(BusinessRecordPo businessRecordPo, List<BusinessRecordPo> changes) {
        if(BusinessPayTypeEnum.RED_PACK.getCode().equals(businessRecordPo.getBusinessPayType())) {
            if(handleRedPack(businessRecordPo)) {
                changes.add(businessRecordPo);
            }
        }
        if(BusinessPayTypeEnum.PAY.getCode().equals(businessRecordPo.getBusinessPayType())) {
            if(handleBusinessPay(businessRecordPo)) {
                changes.add(businessRecordPo);
            }
        }
    }

    public boolean handleRedPack(BusinessRecordPo businessRecordPo){
        BusinessPayVo businessPayVo = new BusinessPayVo();
        businessPayVo.setMchId(businessRecordPo.getMchId());
        businessPayVo.setBusinessOrderType(businessRecordPo.getBusinessOrderType());
        businessPayVo.setPayMode(businessRecordPo.getPayMode());
        businessPayVo.setPayNo(businessRecordPo.getPayNo());
        boolean change = false;
        try {
            BusinessPayQueryBo businessPayQueryBo = wxCommonAdapter.queryRedpack(businessPayVo);
            if("RECEIVED".equals(businessPayQueryBo.getStatus())) {
                businessRecordPo.setStatus(BusinessPayStatusEnum.SUCCESS.getCode());
                businessRecordPo.setSuccessTime(businessPayQueryBo.getSuccessTime());
                change = true;
            }
            if("REFUND".equals(businessPayQueryBo.getStatus())) {
                businessRecordPo.setStatus(BusinessPayStatusEnum.REFUND.getCode());
                businessRecordPo.setSuccessTime(businessPayQueryBo.getSuccessTime());
                change = true;
            }
            if("FAILED".equals(businessPayQueryBo.getStatus())) {
                businessRecordPo.setStatus(BusinessPayStatusEnum.SEND_FAILED.getCode());
                if(StringUtils.isNotEmpty(businessPayQueryBo.getMsg())) {
                    Map<String, String> extraMap;
                    if(StringUtils.isNotEmpty(businessRecordPo.getExtra())) {
                        extraMap = JSONUtils.parse2Map(businessRecordPo.getExtra(), String.class, String.class);
                    } else {
                        extraMap = new HashMap<>(4);
                    }
                    extraMap.put("msg", businessPayQueryBo.getMsg());
                    businessRecordPo.setExtra(JSON.toJSONString(extraMap));
                }
                change = true;
            }
        } catch (PaymentException e) {
            log.error("QueryTradeService#handleRedPack query error businessRecordPo:{}", JSON.toJSONString(businessRecordPo), e);
        }
        return change;
    }

    public boolean handleBusinessPay(BusinessRecordPo businessRecordPo) {
        BusinessPayVo businessPayVo = new BusinessPayVo();
        businessPayVo.setMchId(businessRecordPo.getMchId());
        businessPayVo.setBusinessOrderType(businessRecordPo.getBusinessOrderType());
        businessPayVo.setPayMode(businessRecordPo.getPayMode());
        businessPayVo.setPayNo(businessRecordPo.getPayNo());
        boolean change = false;
        try {
            BusinessPayQueryBo businessPayQueryBo = wxCommonAdapter.queryBusinessPay(businessPayVo);
            if("SUCCESS".equals(businessPayQueryBo.getStatus())) {
                businessRecordPo.setStatus(BusinessPayStatusEnum.SUCCESS.getCode());
                businessRecordPo.setSuccessTime(businessPayQueryBo.getSuccessTime());
                change = true;
            }
            if("FAILED".equals(businessPayQueryBo.getStatus())) {
                businessRecordPo.setStatus(BusinessPayStatusEnum.SEND_FAILED.getCode());
                if(StringUtils.isNotEmpty(businessPayQueryBo.getMsg())) {
                    Map<String, String> extraMap;
                    if(StringUtils.isNotEmpty(businessRecordPo.getExtra())) {
                        extraMap = JSONUtils.parse2Map(businessRecordPo.getExtra(), String.class, String.class);
                    } else {
                        extraMap = new HashMap<>(4);
                    }
                    extraMap.put("msg", businessPayQueryBo.getMsg());
                    businessRecordPo.setExtra(JSON.toJSONString(extraMap));
                }
                change = true;
            }
        } catch (PaymentException e) {
            log.error("QueryTradeService#handleRedPack query error businessRecordPo:{}", JSON.toJSONString(businessRecordPo), e);
        }
        return change;
    }

    public void callBackChanges(List<BusinessRecordPo> businessRecordPos) {
        Map<String ,List<BusinessPayQueryVo>> businessPayQueryVos = new HashMap<>();
        businessRecordPos.forEach(e->convertBusinessPayQueryVo(e, businessPayQueryVos));
        for(String group : businessPayQueryVos.keySet()) {
            // 发送callback request 给 业务
            ResultVO resultVO = ResultVO.createSuccess(businessPayQueryVos.get(group));
            callbackUtil.sendBusinessPayMsg(group, resultVO, Constants.BEGIN_COUNT);
        }
    }
    private void convertBusinessPayQueryVo(BusinessRecordPo businessRecordPo, Map<String ,List<BusinessPayQueryVo>> groupMap){
        BusinessPayQueryVo businessPayQueryVo = new BusinessPayQueryVo();
        businessPayQueryVo.setBusinessNo(businessRecordPo.getBusinessNo());
        businessPayQueryVo.setBusinessPayType(businessRecordPo.getBusinessPayType());
        businessPayQueryVo.setStatus(businessRecordPo.getStatus());
        if(BusinessPayStatusEnum.SUCCESS.getCode().equals(businessRecordPo.getStatus())) {
            businessPayQueryVo.setSuccessTime(businessRecordPo.getSuccessTime());
        } else {
            if(StringUtils.isNotEmpty(businessRecordPo.getExtra())) {
                Map<String, String> extraMap = JSONUtils.parse2Map(businessRecordPo.getExtra(), String.class, String.class);
                businessPayQueryVo.setMsg(extraMap.get("msg"));
            }
        }
        if(groupMap.containsKey(businessRecordPo.getCallback())) {
            groupMap.get(businessRecordPo.getCallback()).add(businessPayQueryVo);
        } else {
            List<BusinessPayQueryVo> list = new ArrayList<>();
            list.add(businessPayQueryVo);
            groupMap.put(businessRecordPo.getCallback(), list);
        }
    }

    /**
     * 生成待冻结账单
     * @param accountId
     * @param items
     */
    private void genFrozenSettlementOrder0(String accountId, String businessOrderType, List<PayResultOrder> items) throws Exception {
        /**
         * 未开户完成不生成冻结账单
         */
        if(!checkOpenAccountComplete(accountId, ChannelProductConstants.QIFUTONG)) {
            log.warn("FrozenSettlementService#genFrozenSettlementOrder0 not open account complete, accountId={}," +
                    "businessOrderType={}", accountId, businessOrderType);
            return;
        }

        // 1.查询账户
        ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);

        if(thirdUserInfo == null) {
            throw new PaymentException(ResultCodeEnum.THIRD_USER_ID_NOT_EXIST);
        }

        // 2.组装数据
        Date tradeDate = items.get(NumberUtils.INTEGER_ZERO).getCtime();
        FrozenSettlement frozenSettlement = FrozenSettlement.build(ybmSpringConfiguration.merchantNo(), accountId, thirdUserInfo.getThirdUserId(),
                businessOrderType, FBankTradeTypeEnum.SETTLE.getType(), getFBankAmount(items), getTradeDate(tradeDate), getFrozenDate(tradeDate));
        List<FrozenSettlement> oldData = frozenSettlementService.queryFrozenSettlement(frozenSettlement);

        if(!CollectionUtils.isEmpty(oldData)) {
            log.warn("FrozenSettlementService#genFrozenSettlementOrder0 already exit, accountId={}," +
                    "businessOrderType={}, items={}", accountId, businessOrderType, JSONObject.toJSONString(items));
            return;
        }

        frozenSettlement.setStatus(FrozenStatusEnum.FROZEN_WAIT.getStatus());
        frozenSettlement.setMessage(FrozenStatusEnum.FROZEN_WAIT.getDesc());

        // 3.写入
        if(frozenSettlementService.insert(frozenSettlement) != NumberUtils.INTEGER_ONE) {
            throw new PaymentException("Insert FrozenSettlement exception.");
        }
    }

    /**
     * 富民交易金额
     * @param items
     * @return
     */
    private String getFBankAmount(List<PayResultOrder> items) {
        Integer amount = 0;

        for(PayResultOrder item : items) {
            if(item.getPayChannel().contains(ChannelConstants.CHANNEL_FUMIN_BANK_NAME)) {
                amount += item.getAmount();
            }
        }

        return AmountCastUtil.castFen2Yuan(amount);
    }

    /**
     * 交易时间
     * @return
     */
    private Date getTradeDate(Date tradeDate) throws ParseException {
        return ConcurrentSimpleDateFormatUtil.parse(ConcurrentSimpleDateFormatUtil.
                format(tradeDate, DateUtil.DATEFORMATDAY), DateUtil.DATEFORMATDAY);
    }

    /**
     * 应冻结时间
     * @return
     */
    private Date getFrozenDate(Date tradeDate) throws Exception {
        /**
         * 节假日映射
         */
        Map<String, String> frozenDateMap = JSONUtils.parse2Map(ApolloUtil.getProperty("map_frozen_date"), String.class, String.class);
        String format = DateUtil.format(tradeDate, DateUtil.DATEFORMATDAY);

        if(frozenDateMap != null && frozenDateMap.containsKey(format)) {
            return DateUtil.parase(frozenDateMap.get(format), DateUtil.DATEFORMATDAY);
        }

        /**
         * 周五周六周天 应冻结日期是下周一
         */
        String weekDay = DateUtil.getWeekDay(tradeDate);

        switch(weekDay) {
            case DateUtil.W1:
            case DateUtil.W2:
            case DateUtil.W3:
            case DateUtil.W4:
                return DateUtil.getNextDay(tradeDate);
            case DateUtil.W5:
            case DateUtil.W6:
            case DateUtil.W7:
                return DateUtil.getNextWeekMonday(tradeDate);
        }

        throw new PaymentException("Get FrozenDate Error.");
    }

    /**
     * 校验用户是否开户成功 流程走完+富民开通支付功能配置完成
     * @param accountId 平台账户
     * @param channelProduct 渠道
     * @return
     */
    public boolean checkOpenAccountComplete(String accountId, String channelProduct) {
        ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);

        if(thirdUserInfo == null || thirdUserInfo.getUserId().equals(thirdUserInfo.getThirdUserId())) {
            return false;
        }

        // 查询微信开户意愿申请单
        ApplyOpenAccountStatus queryParam = new ApplyOpenAccountStatus();
        queryParam.setAccountId(accountId);
        queryParam.setThirdUserId(thirdUserInfo.getThirdUserId());
        List<ApplyOpenAccountStatus> applyOpenAccountStatuses = applyOpenAccountStatusService.selectByParam(queryParam);

        if(applyOpenAccountStatuses.size() != 1) {
            return false;
        }

        // 未授权代表开户未完成
        ApplyOpenAccountStatus applyOpenAccountStatus = applyOpenAccountStatuses.get(0);

        if(applyOpenAccountStatus.getAuthorize() != OpenAccountAuthorizeStatusEnum.AUTHORIZE_STATE_AUTHORIZED.getStatus()) {
            return false;
        }

        // 查询支付功能
        ApplypayUserInfo applypayUserInfo = applypayUserInfoService.queryUserInfoByAccountId(accountId);
        List<OpenpayInfo> openpayInfos = openpayInfoService.queryUserInfoByAccountId(accountId, applypayUserInfo.getThirdUserInfoId());

        for(OpenpayInfo openpayInfo : openpayInfos) {
            if(FBankPowerIdEnum.WX_MINI.getPowerId().equals(openpayInfo.getPowerId())
                    || FBankPowerIdEnum.WX_OFFICIAL.getPowerId().equals(openpayInfo.getPowerId()))
            {
                if(!OpenPayStatusEnum.SUCCESS_PAY_CHANNEL.getStatus().equals(openpayInfo.getStatus())) {
                    // 如果富民配置没完成 算开户未成功
                    return false;
                }
            }
        }

        return true;
    }
}
